package calorie.com.calorie.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxh.baselibray.dialog.AlertDialog;
import com.lxh.baselibray.mvp.MvpActivity;
import com.lxh.baselibray.net.ServiceGenerator;
import com.lxh.baselibray.util.Md5Utils;
import com.lxh.baselibray.util.SPUtils;
import com.lxh.baselibray.util.SizeUtils;
import com.lxh.baselibray.util.ToastUtils;
import com.lxh.baselibray.view.PswText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import calorie.com.calorie.R;
import calorie.com.calorie.adapter.GoodsDetailPicAdapter;
import calorie.com.calorie.constant.Constant;
import calorie.com.calorie.contact.BuyGoodsContact;
import calorie.com.calorie.response.BuyGoodsResponce;
import calorie.com.calorie.response.GoodsListResponce;
import calorie.com.calorie.util.LiWindow;
import retrofit2.Response;

//购买商品
public class MallBuyGoodsActivity extends MvpActivity<BuyGoodsContact.BuyGoodsPresent> implements BuyGoodsContact.IBuyGoodsView {

    @BindView(R.id.goods_banner_pic)//头部图片
            ImageView goodsBannerPic;
    @BindView(R.id.goods_name)//商品名
            TextView goodsName;
    @BindView(R.id.goods_price)//商品价格
            TextView goodsPrice;
    @BindView(R.id.goods_no)//商品编号
            TextView goodsNo;
    @BindView(R.id.minus_btn)//减少购买商品数量  最少为1
            ImageButton minusBtn;
    @BindView(R.id.edit_goods_number)//显示所购买商品的数量
            EditText editGoodsNumber;
    @BindView(R.id.add_btn)//增加购买商品数量  不超过库存数量
            ImageButton addBtn;
    @BindView(R.id.goods_selected_info)//所选商品的信息显示
            TextView goodsSelectedInfo;
    @BindView(R.id.sure_btn)//确定购买
            TextView sureBtn;

    @BindView(R.id.rp_one)
    RadioGroup rpOne;
    private ImageView big_show;
    GoodsListResponce.DataBean.GoodsListBean bean;
    String goodsAttribute;
    String detailUrl;
    int count;
    int stock;//库存
    @BindView(R.id.attribute_name)
    TextView attributeName;


    List<GoodsListResponce.DataBean.GoodsListBean> mList;
    @BindView(R.id.stock_tx)
    TextView stockTx;
    @BindView(R.id.stock_num)
    TextView stockNum;
    @BindView(R.id.rv)
    RecyclerView rv;
    GoodsDetailPicAdapter mAdapter;
    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            String goods = intent.getStringExtra("goods");
            bean  =  JSONObject.parseObject(goods,GoodsListResponce.DataBean.GoodsListBean.class);


            initAttribute();


            initGoodsPic();


            initGoodsDetail();
        }
    }

    //商品列表详情图片
    private void initGoodsPic(){

            GoodsDetailPicAdapter mAdapter = new GoodsDetailPicAdapter(R.layout.goods_detail_item,bean.getDetailUrl());
            LinearLayoutManager manager = new LinearLayoutManager(context);
            rv.setLayoutManager(manager);
            rv.setAdapter(mAdapter);



//            Glide.with(this).load(ServiceGenerator.BASE_URL + ":9023/image/" + bean.getDetailUrl().get(i)).into(imageView);//显示商品详情图片

        mAdapter.notifyDataSetChanged();
    }


    RadioButton rb;

    private void initAttribute() {
        for (int i = 0; i < bean.getGoodsAttribute().size(); i++) {
            RadioButton radioButton = (RadioButton) LayoutInflater.from(context).inflate(R.layout.item_radiobutton, null, false);
            radioButton.setId(i);
            radioButton.setText(bean.getGoodsAttribute().get(i).getAttribute());
            rpOne.addView(radioButton);
            if (0 == i) {
                rpOne.check(0);
                stockTx.setVisibility(View.VISIBLE);
                attributeName.setText(bean.getGoodsAttribute().get(0).getAttribute());
                stockNum.setText(bean.getGoodsAttribute().get(0).getStock());
            }
        }
        rpOne.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                rb = rpOne.findViewById(checkedId);
                editGoodsNumber.setText(Integer.toString(1));
                attributeName.setText(rb.getText());
                stockTx.setVisibility(View.VISIBLE);
                stockNum.setText(bean.getGoodsAttribute().get(checkedId).getStock());
                stock = Integer.parseInt(stockNum.getText().toString().trim());
                if (stock == 0) {
                    editGoodsNumber.setEnabled(false);
                    ToastUtils.showShortToast(context, "亲，所选商品没有货了！");
                    minusBtn.setEnabled(false);
                    addBtn.setEnabled(false);
                    return;
                } else {
                    editGoodsNumber.setEnabled(true);
                    minusBtn.setEnabled(true);
                    addBtn.setEnabled(true);
                }

//                Toast.makeText(MainActivity.this, rb.getId() + "", Toast.LENGTH_SHORT).show();

            }
        });
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_mall_buy_goods;
    }

    @Override
    protected BuyGoodsContact.BuyGoodsPresent createPresent() {
        return new BuyGoodsContact.BuyGoodsPresent();
    }

    //显示商品数据
    private void initGoodsDetail() {
        Glide.with(this).load(ServiceGenerator.BASE_URL + ":9023/image/" + bean.getImgUrl()).into(goodsBannerPic);//显示banner图片
        goodsName.setText(bean.getTitle());//商品名
        goodsPrice.setText(bean.getPrice() + "  CAL");//商品价格
        goodsNo.setText(bean.getId());//商品编号
        goodsSelectedInfo.setText(goodsName.getText().toString());//已选商品属性

       // Glide.with(this).load(ServiceGenerator.BASE_URL + ":9023/image/" + detailUrl).into(goodsDetailPic);//显示商品详情图片
    }


    @OnClick({R.id.goods_banner_pic,R.id.minus_btn, R.id.edit_goods_number, R.id.add_btn, R.id.sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.goods_banner_pic://点击放大
                LiWindow showCode = new LiWindow(context);
                View view2 = LayoutInflater.from(context).inflate(R.layout.good_pic_big, null);
                big_show = (ImageView) view2.findViewById(R.id.big_show);
                Glide.with(this).load(ServiceGenerator.BASE_URL + ":9023/image/" + bean.getImgUrl()).into(big_show);//显示banner图片
                showCode.showCenterMatchParent(view2);
                big_show.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showCode.closePopupWindow();
                    }
                });
                break;
            case R.id.minus_btn://减少商品数量
                count = Integer.parseInt(editGoodsNumber.getText().toString());
                if (count > 1) {
                    count -= 1;
                }
                editGoodsNumber.setText(Integer.toString(count));
                break;
            case R.id.edit_goods_number://点击显示光标
                editGoodsNumber.setCursorVisible(true);
                break;
            case R.id.add_btn://增加商品数量
                count = Integer.parseInt(editGoodsNumber.getText().toString());
                stock = Integer.parseInt(stockNum.getText().toString().trim());
                if (count < stock) {
                    count += 1;
                }
                editGoodsNumber.setText(Integer.toString(count));
                break;
            case R.id.sure_btn:
                int userId = SPUtils.getInt(Constant.USER_ID, -1, context);//用户id
                String goodsId = goodsNo.getText().toString();//商品编号
                int count = Integer.parseInt(editGoodsNumber.getText().toString());//商品数量
                String goodsAttribute = attributeName.getText().toString();//商品属性

                stock = Integer.parseInt(stockNum.getText().toString().trim());
                if (stock == 0) {
                    ToastUtils.showLongToast(context, "该商品此款式没有货了，请选择其他商品");
                    return;
                }
                showDealDialog(userId, goodsId, count, goodsAttribute);
                break;
        }
    }

    AlertDialog dealDialog = null;

    private void showDealDialog(Integer userId, String goodsId, Integer count, String goodsAttribute) {//交易密码弹窗
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .addDefaultAnimation()
                .setCancelable(true)
                .setContentView(R.layout.dialog_deal_pwd)
                .setWidthAndHeight(SizeUtils.dp2px(context, 279), SizeUtils.dp2px(context, 157))
                .setOnClickListener(R.id.tv_sure, v -> {
                    PswText psw = dealDialog.getView(R.id.pt_deal_pwd);
                    String dealPwd = Md5Utils.stringToMD5(psw.getPsw());
                    mPresent.buyGoods(context, userId, dealPwd, goodsId, count, goodsAttribute);
                    dealDialog.dismiss();

                }).setOnClickListener(R.id.tv_cancle, v -> dealDialog.dismiss());
        dealDialog = builder.create();
        dealDialog.show();
    }


    //购买商品返回
    @Override
    public void getBuyGoodsResult(Response<BuyGoodsResponce> response) {
        if (response.body().getCode() == Constant.SUCCESS_CODE) {
            ToastUtils.showLongToast(context, "商品购买成功！请到待发货查看");
            finish();
        } else {
            ToastUtils.showLongToast(context, response.body().getMsg());
        }
    }

}
